<template>
  <div class="CitySearch">
    <input type="text" v-model="keyWord" placeholder="请输入搜索内容">
    <div class="search-content">
      <ul v-show="keyWord">
        <li v-for="item in list" :key="item.id" @click="selectCity(item.name)">
          {{ item.name }}
        </li>
        <li v-show="!list.length">没有搜索到相关内容</li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: "CitySearch",
  data() {
    return {
      keyWord: '',
      list: [],
      timer: null
    }
  },
  props: {
    cities: Object
  },
  methods: {
    selectCity(city) {
      this.$store.dispatch('selectCity', city)
      this.$router.push('/')
    }
  },
  watch: {
    keyWord() {
      if (!this.keyWord) {
        this.list = [];
        return;
      }
      if (this.timer) return;
      this.timer = setTimeout(() => {
        let arr = [];
        for (let key in this.cities) {
          this.cities[key].forEach(element => {
            if (element.name.indexOf(this.keyWord) != -1 || element.spell.indexOf(this.keyWord) != -1) {
              arr.push(element)
            }
          });
        }
        this.list = arr;
        this.timer = null
      }, 100)
    }
  },
  // mounted() {
  //   this.scroll = new BScroll(this.$refs.warpper, {
  //     click: false
  //   })
  // }
}
</script>

<style lang="less" scoped>
.CitySearch {
  height: .6rem;
  padding: .2rem;
  background-color: #00bcd4;
  position: sticky;
  top: .68rem;
  z-index: 999;

  input {
    display: block;
    width: 100%;
    height: 100%;
    border: 0;
    outline: 0;
    box-sizing: border-box;
    padding-left: .5rem;
    border-radius: .08rem;
  }

  .search-content {
    background-color: #fff;

    li {
      font-size: .32rem;
      line-height: .6rem;
      padding-left: .2rem;
      border-bottom: 1px solid #ccc;

      &:last-child {
        border-bottom: 0;
      }
    }
  }
}
</style>